package common

import (
	"encoding/json"
	"errors"
	"github.com/qiniu/x/log"
	"net/http"
)

const (
	APP_KEY = "abf14f9bb45544898f81a45ab374f1f2"
	URL     = "http://eid.shumaidata.com/eid/check"
)

func Authentication(cardName, idNumber string) (string, error) {
	//todo:构建请求参数
	payload := URL + "?idcard=" + idNumber + "&name=" + cardName
	client := &http.Client{}
	req, err := http.NewRequest("POST", payload, nil)
	if err != nil {
		log.Panicln("创建http客户端失败")
		return "", errors.New("创建http客户端失败")
	}

	//todo:设置头部
	req.Header.Set("Authorization", "APPCODE "+APP_KEY)

	//todo:发送http请求
	res, err := client.Do(req)
	if err != nil {
		log.Panicln("发送http请求失败")
		return "", errors.New("发送http请求失败")
	}
	defer res.Body.Close()

	//todo:转换返回指类型
	var m map[string]interface{}
	err = json.NewDecoder(req.Body).Decode(&m)
	if err != nil {
		log.Panicln("类型转换失败")
		return "", errors.New("类型转换失败")
	}

	r, ok := m["result"].(map[string]interface{})
	if !ok {
		log.Panicln("未查找到结果")
		return "", errors.New("未查找到结果")
	}

	return r["description"].(string), nil
}
